package plus.xj17520.org.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import plus.xj17520.org.domain.User;
import plus.xj17520.org.mapper.UserMapper;
import plus.xj17520.org.service.IUserService;
import plus.xj17520.base.utils.MyStringUtil;
import plus.xj17520.base.query.UserQuery;
import plus.xj17520.base.result.JSONResult;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @projectName: pethomeProject
 * @package: plus.xj17520.org.service.impl
 * @className: UserServiceImpl
 * @author: XiaoJue
 * @description: TODO
 * @date: 2022/5/23 15:36
 * @version: 1.0
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public JSONResult addOrUpdate(User user) {
        if (user.getId() != null) {
            Date date = new Date();
            user.setUpdateTime(date);
            userMapper.updateByPrimaryKey(user);
        }
        else
            userMapper.insert(user);
        return JSONResult.success();
    }

    @Override
    public JSONResult findOne(Long id) {
        return JSONResult.success(userMapper.selectByPrimaryKey(id));
    }

    @Override
    public JSONResult findAll() {
        List<User> users = userMapper.selectAll();
        return JSONResult.success(users);
    }

    @Override
    public JSONResult delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
        return JSONResult.success();
    }

    @Override
    public JSONResult userPageList(UserQuery userQuery) {
        Example example = new Example(User.class);
        if (MyStringUtil.isNotEmpty(userQuery.getKeyword()))
            //模糊查询
            example.and().andLike("username", "%" + userQuery.getKeyword() + "%");
        if (MyStringUtil.isNotEmpty(userQuery.getEmail()))
            //精确查询
            example.and().andEqualTo("email", userQuery.getEmail());

        //分页
        PageHelper.startPage(userQuery.getCurrent(), userQuery.getSize());
        List<User> users = userMapper.selectByExample(example);
        //返回查询结果集
        return JSONResult.success(new PageInfo<>(users));
    }

    @Override
    public JSONResult batchDelete(UserQuery userQuery) {
        Long[] ids = userQuery.getIds();
        for (Long id : ids)
            userMapper.deleteByPrimaryKey(id);
        return JSONResult.success();
    }

}
